package com.moon.app;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Pattern;

import org.apache.commons.lang.StringUtils;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.EditText;
import android.widget.Toast;

import com.beardedhen.androidbootstrap.BootstrapButton;
import com.moon.R;
import com.moon.common.AbstractActivity;
import com.moon.constants.MoonConstants;
import com.moon.model.UserJsonResult;
import com.moon.utils.HttpClientUtils;
import com.moon.utils.JacksonUtils;
import com.moon.utils.SharedPreferencesUtils;

/**
 * 重置密码--找回密码
 * 
 * @author paul
 * @date 2014年5月3日
 */
public class ResetPasswordActivity extends AbstractActivity{

    private static final String TAG = ResetPasswordActivity.class.getSimpleName();

    private EditText            email;
    private EditText            password;
    private EditText            validateCode;

    private BootstrapButton     resetPasswordBtn;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.reset_password);

        email = (EditText) findViewById(R.id.editLoginAccount);
        String emailText = getIntent().getStringExtra(MoonConstants.USER_EMAIL);
        email.setText(emailText);
        
        
        password = (EditText) findViewById(R.id.editLoginPassword);
        validateCode = (EditText) findViewById(R.id.editValidateCode);
        resetPasswordBtn = (BootstrapButton) findViewById(R.id.buttonResetPassword);
        resetPasswordBtn.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                //重置密码
                String message = validate();
                if (StringUtils.isNotBlank(message)) {
                    Toast.makeText(getApplicationContext(), message, Toast.LENGTH_SHORT).show();
                    return;
                }
                new ResetPasswordTask().execute(email.getText().toString(), password.getText()
                        .toString(), validateCode.getText().toString());

            }
        });

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        //getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    private class ResetPasswordTask extends AsyncTask<String, String, Boolean> {
        String requeyUrl = "/mobile_user/resetpassword.do";

        @Override
        protected Boolean doInBackground(String... params) {
            try {
                //请求服务器
                List<NameValuePair> pairs = convertParams(params);
                String json = HttpClientUtils.post(MoonConstants.MOON_DOMAIN + requeyUrl, pairs);
                UserJsonResult result = JacksonUtils.fromJSON(json, UserJsonResult.class);
                if (result.isSuccess()) {
                    //写用户共享数据
                    writeSharedData(result);
                    //成功回登录
                    Intent intent = new Intent(ResetPasswordActivity.this, MainActivity.class);
                    startActivity(intent);
                    return true;
                } else {
                    if (StringUtils.isNotBlank(result.getMessage())) {
                        publishProgress(result.getMessage());
                    }
                    return false;
                }
            } catch (Exception e) {
                // 提示用户网络异常
                String message = getString(R.string.network_error);
                Log.e(TAG, message, e);
                publishProgress(message);
                return false;
            }
        }

        /**
         * 这里的Intege参数对应AsyncTask中的第二个参数
         * 在doInBackground方法当中，，每次调用publishProgress方法都会触发onProgressUpdate执行
         * onProgressUpdate是在UI线程中执行，所有可以对UI空间进行操作
         */
        @Override
        protected void onProgressUpdate(String... values) {
            Toast.makeText(getApplicationContext(), values[0], Toast.LENGTH_SHORT).show();
        }

        /**
         * 组装request参数
         * 
         * @param params
         * @return
         */
        private List<NameValuePair> convertParams(String... params) {
            List<NameValuePair> pairs = new ArrayList<NameValuePair>();
            pairs.add(new BasicNameValuePair(MoonConstants.USER_EMAIL, params[0]));
            pairs.add(new BasicNameValuePair(MoonConstants.USER_PASSWORK, params[1]));
            pairs.add(new BasicNameValuePair(MoonConstants.USER_VALIDATE_CODE, params[2]));
            return pairs;
        }

        /**
         * 写入用户信息
         */
        private void writeSharedData(UserJsonResult result) {
            SharedPreferences shareDate = getSharedPreferences(
                    MoonConstants.SHARED_PREFERENCES_KEY, Context.MODE_PRIVATE);
            SharedPreferencesUtils.writeUserData(shareDate, result.getObject());
        }
    }

    /**
     * 注册校验
     * 
     * @return
     */
    private String validate() {
        if (!Pattern.matches(
                "^([a-zA-Z0-9_\\.\\-])+\\@(([a-zA-Z0-9\\-])+\\.)+([a-zA-Z0-9]{2,4})+$", email
                        .getText().toString())) {
            return "邮箱格式不正确";
        }

        if (email.getText().toString().length() > 128) {
            return "邮箱太长,不能超过128个字符";
        }

        if (password.getText().toString().length() < 6) {
            return "密码长度至少6位";
        }
        if (password.getText().toString().length() > 128) {
            return "密码太长,不能超过128个字符";
        }

        if (StringUtils.isBlank(validateCode.getText().toString())) {
            return "验证码不能为空";
        }

        if (validateCode.getText().toString().length() > 256) {
            return "验证码太长,不能超过128个字符";
        }
        return null;
    }

}
